package com.jumi.microservice.common.config;

import com.jumi.microservice.common.constant.RequestConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;


/**
 * @author Administrator
 */
@WebFilter
@Component
public class AuthHeaderSettingFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper((HttpServletRequest) request) {

            @Override
            public String getHeader(String name) {
                String superHeader = super.getHeader(name);
                if(RequestConstant.ADMIN_NAME.equals(name) && !StringUtils.isEmpty(superHeader)){
                    try {
                        return URLDecoder.decode(superHeader, "utf8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                return superHeader;
            }
        };
        chain.doFilter(requestWrapper,response);
    }

    @Override
    public void destroy() {
    }
}